﻿#include "line_arc_intersect.h"

double Distance(Point a,Point b){

    return std::sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}



double Arc::NormalizeAngle(double angle) {

    while (angle < 0)    angle += 2 * M_PI;
    while (angle >= 2 * M_PI) angle -= 2 * M_PI;

    return angle;
}

bool Arc::IsPointInArc(Point p) {
    double angle = atan2(p.y - center.y, p.x - center.x);
    angle = NormalizeAngle(angle);


    if (startangle <= endangle) {
        return angle >= startangle && angle <= endangle;
    }
    else {
        return angle >= startangle || angle <= endangle;
    }
}




bool Arc::FindInterSections(Point p1, Point p2, std::vector<Point>& intersections) {

    double dx = p2.x - p1.x;
    double dy = p2.y - p1.y;
    double fx = p1.x - center.x;
    double fy = p1.y - center.y;


    double a = dx * dx + dy * dy;
    double b = 2 * (fx * dx + fy * dy);
    double c = (fx * fx + fy * fy) - radius * radius;

    double det = b * b - 4 * a * c;

    if (det < 0) {
        return false;
    }

    double t1 = (-b - sqrt(det)) / (2 * a);
    double t2 = (-b + sqrt(det)) / (2 * a);

    if (t1 >= 0 && t1 <= 1) {
        Point p = { p1.x + t1 * dx,p1.y + t1 * dy };
        if (IsPointInArc(p))    intersections.push_back(p);
    }

    if (t2 >= 0 && t2 <= 1 && det > 0) {
        Point p = { p1.x + t2 * dx,p1.y + t2 * dy };
        if (IsPointInArc(p))    intersections.push_back(p);
    }

    return !intersections.empty();

}



double RandomDouble(double min, double max) {
    static std::mt19937 generator(static_cast<unsigned int>(std::time(nullptr)));
    std::uniform_real_distribution<double> distribution(min, max);
    return distribution(generator);
}


